package com.generation.builder;

import com.generation.Bean.Constants;
import com.generation.Bean.TableInfo;
import com.generation.utils.DateUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Map;
import java.util.Properties;

/**
 * @author mockingjay
 * @date 2023/4/16 - 15:16
 */
public class BuildMapper {

    private static final Logger LOGGER = LoggerFactory.getLogger(BuildMapper.class);

    public static void excute(TableInfo tableInfo){
        File folder =new File(Constants.PATH_MAPPER);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String className=tableInfo.getBeanName()+Constants.SUFFIX_MAPPER;
        File poFile=new File(folder,className+".java");

        OutputStream out=null;
        OutputStreamWriter ow=null;
        BufferedWriter bw=null;
        try {
            out=new FileOutputStream(poFile);
            ow=new OutputStreamWriter(out,"utf8");
            bw=new BufferedWriter(ow);
            //配置velocity资源加载器
            Properties prop = new Properties();
            prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            Velocity.init(prop);
            //封装mapper模板数据
            Map <String,Object> mapperTemplateData=Constants.TEMPLATE_DATA;
            mapperTemplateData.put("className",className);
            mapperTemplateData.put("datetime", DateUtils.getNowDate());
            mapperTemplateData.put("comments",tableInfo.getComment()+"mapper");
            mapperTemplateData.put("classPoName",tableInfo.getBeanName());
            VelocityContext context = new VelocityContext(mapperTemplateData);
            String templatePath=Constants.TEMPLATE_MAPPER;
            Template tpl = Velocity.getTemplate(templatePath, "UTF-8");
            tpl.merge(context, bw);
        }catch (Exception e){
            LOGGER.error("创建mapper失败",e);
        }finally {
            if(bw!=null){
                try {
                    bw.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if(ow!=null){
                try {
                    ow.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if(out!=null){
                try {
                    out.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}
